import React from 'react';
import * as Tools from '@utils/tools';
import './index.css'

//新增useImgHeight参数，默认为true，如果为真则用图片高度，为假则用设定的height

export default class ImgPlaceHold extends React.Component {



	constructor(props) {
		super(props);
		// console.log((this.props.width&&`${Tools.px2rem(this.props.width)}` )|| "10rem","2222222222222")
		this.state = {
			showImg: false,
			src: "",
			width: (this.props.width&&`${Tools.px2rem(this.props.width)}` )|| "10rem",
			height: (this.props.height&&`${Tools.px2rem(this.props.height)}`)|| "2.5rem",
		}
	}

	static defaultProps = { 
		useImgHeight: true
	}

	componentDidMount() {
		var { children } = this.props
		this.updataImg(children.props.src)
	}

	componentWillMount() {

	}

	componentWillReceiveProps(nextProps) {
		var oldChildren = this.props.children
		var { children } = this.props
		if (children.props.src != oldChildren.props.src) {
			this.updataImg(children.props.src)
		}
	}

	updataImg = (src) => {
		var _this =this;
		var img = new Image()
		var width = this.fixPX2Num(this.props.width);
		var height = this.fixPX2Num(this.props.height);
		var wd = 0;
		
		if (width == "100%") {
			wd = 750;
		} else{
			wd = width
		}
		img.src = src;
		img.onload = () => {
			var imgWidth = img.width;
			var imgHeight = img.height;
			_this.setState({
				showImg: true,
				src: src,
				width: Tools.px2rem(wd),
				height: this.props.useImgHeight?Tools.px2rem(((wd / imgWidth) * imgHeight)):Tools.px2rem(height),
			})
		}
	}

	fixPX2Num=(value)=>{
		if(typeof(value)=='string'&&value.indexOf("px")>-1){
			value = Number(value.split("px")[0])
			return value
		  }else{
			return value
		  }
	}

	render() {
		var { src, showImg, height, width } = this.state
		return (
			<div className={`${this.props.className} imgPlaceHoldBox ${Tools.inIos()?"":"hasAnimate"}`} 
				style={{...this.props.style,width:width,height:height}}
			>
				{
					showImg ?
						<img {...this.props.children.props} style={{height:"100%",width:"100%"}} />
						:
						<div className="loadBox"
							style={{ width: width, height: height }}
						>
							<div className="loading1">
								<span></span>
								<span></span>
								<span></span>
								<span></span>
								<span></span>
							</div>
						</div>

				}
			</div>
		)
	}
}